package com.zzj.ecology.framework.configs.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;

@Component
public class CustomizeFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {

    @Autowired
    private CustomizeFilterInvocationSecurityMetadataSource securityMetadataSource;

    @Override
    @Autowired
    public void setAccessDecisionManager(@Qualifier("accessDecisionManager") AccessDecisionManager accessDecisionManager) {
         super.setAccessDecisionManager(accessDecisionManager);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        FilterInvocation filterInvocation = new FilterInvocation(request, response, chain);
        // filterInvocation 有一个被拦截的URL
        // filterInvocation 调用 com.zeng.boot.web.security.CustomFilterInvocationSecurityMetadataSource.getAttributes(Object object)
        // 方法获取所有的权限, 再调用 com.zeng.boot.web.security.CustomAccessDecisionManager 校验用户权限是否足够
        InterceptorStatusToken token = super.beforeInvocation(filterInvocation);
        try {
            // 执行下一个过滤器
            filterInvocation.getChain().doFilter(filterInvocation.getHttpRequest(), filterInvocation.getResponse());
        } finally {
            super.afterInvocation(token, null);
        }
    }

    @Override
    public void destroy() {

    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return this.securityMetadataSource;
    }
}
